package com.hxx.day8;

public class TestDemo7 {
    public static void main(String[] args) {
        Demo demo = new Demo();
        //同一个对象创建两个线程，互相唤醒
        new Product(demo);
        new Consumer(demo);
    }
}
class Demo{
    int value;
    boolean flag = false;

    public synchronized int getValue() {
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = false;
        }
        notify();
        System.out.println("-------getValue------");
        return value;
    }

    public synchronized void setValue(int value) {
        if(!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true;
        }
        notify();
        System.out.println("-------setValue------");
        this.value = value;
    }
}

//生成者
class Product implements Runnable{
    private Demo demo;
    public Product(Demo demo){
        this.demo = demo;
        new Thread(this).start();
    }

    @Override
    public void run() {
        int i = 0;
        while (true){
            System.out.println("生成者--->"+i);
            demo.setValue(i++);
        }
    }
}
//消费者
class Consumer implements Runnable{
    private Demo demo;
    public Consumer(Demo demo){
        this.demo = demo;
        new Thread(this).start();
    }
    @Override
    public void run() {
        while (true){
            System.out.println("消费者:"+demo.getValue());
        }
    }
}